<template>
  <div class="statistics">
    <div class="box-right">
      <app-map ref="workmap" mapHeight="100vh" :propModels="models" mapWidth="100%">
        <template #search>
          <div class="boundary-topleft">
            <el-input v-model="models.searchName" clearable suffix-icon="el-icon-search" @click.native="startSearch">
            </el-input>
          </div>
        </template>
        <template #menu>
          <div class="boundary-left">
            <data-param-menu @handleSelect="handleSelect"></data-param-menu>
          </div>
        </template>
        <template #right>
          <div class="boundary-right">
            <flood-card @reset="reset" :models="models" @updateRadiusKm="updateRadiusKm" @simulate="simulate"
              @clearDrawing="clearDrawing" @startDrawing="startDrawing" @updateFloodArea="updateFloodArea"></flood-card>
          </div>
        </template>
        <template #bootom>
          <div class="boundary-bootom">
            <flood-info-card :models="data"></flood-info-card>
          </div>
        </template>
      </app-map>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator';
import AppMap from "@/components/AppMap.vue";
import FloodCard from "@/views/app/components/FloodCard.vue";
import WorkTree from "@/views/region/components/WorkTree.vue";
import DataParamMenu from '@/views/app/components/DataParamMenu.vue';
import FloodInfoCard from '@/views/app/components/FloodInfoCard.vue';

import { geoJson } from '@/api/investDataCommon';
import { searchIndex, commonInfo } from '@/api/findData';
import moment from 'moment';
import _ from 'lodash';
@Component({
  methods: {},
  components: { WorkTree, AppMap, DataParamMenu, FloodCard, FloodInfoCard }
})
export default class applyUse extends Vue {

  @Ref("workmap") workmap;
  private waterLevelList: any = [];


  private data: any = {
    disasterData: null,

  }
  debouncedHandleSearch;

  models: any = {
    searchName: '',
    workId: '',
    isDrawing: false,
    waterLevel: 0,
    updateRadiusKm: 0,
    hasWater: false,
    area: 0,
  }

  handleSelect(item) {
    const findIds = this.workmap.findFeature();
    if (findIds.length == 0) {
      this.$message.info("在指定区域内没有找到数据");
      return;
    }
    

    this.$message.success(`在指定区域内找到${findIds.length}条数据`);
    searchIndex({
      workId: this.models.workId,
      index: item.id,
      ids: findIds,
    }).then(res => {
      this.workmap.buildChartIndex(res.data);
    });
  }

  private simulate() {

    const floodIds = this.workmap.findFloodFeatures();

    commonInfo({
      ids: floodIds,
    }).then(res => {
      this.data.disasterData = res.data;
      const stat = {
        affectedPopulation: res.data.indexMap["1"] /10000,
        affectedArea: (this.models.area / 1000000),
        affectedCount: res.data.departInfo.length,
      };
   
      (this as any).$bus.$emit("disasterStatus", stat);
      (this as any).$bus.$emit('waterLevelListHandler', this.waterLevelList);
      const wuzichubei =  this.extractIndexData( this.data.disasterData,"0");
      (this as any).$bus.$emit("materialData", wuzichubei);
      (this as any).$bus.$emit("disasterData",  this.data.disasterData);
    });


    const floodOtherIds = this.workmap.findOtherFeatures();
    if(floodOtherIds && floodOtherIds.length > 0){
      commonInfo({
        ids: floodOtherIds,
      }).then(res => {
        const wuzichubei =  this.extractIndexData( res.data,"0");
        (this as any).$bus.$emit("regionsMaterialData", wuzichubei);
        const jiuyuannengli =  this.extractIndexData( res.data,"2");
        (this as any).$bus.$emit("rescueCapability", jiuyuannengli);
      });
    }
  }
  updateFloodArea() {
    this.workmap.updateFloodArea(this.models.waterLevel);
    this.waterLevelList.push({ value: this.models.waterLevel, time: moment(new Date()).format('yyyy-MM-DD HH:mm:ss') });
    if (this.models.area > 0) {
      (this as any).$bus.$emit('waterLevelListHandler', this.waterLevelList);
    }

  }
  reset() {
    this.workmap.reset();
    (this as any).$bus.$emit("disasterStatus", {
      affectedPopulation: 0,
      affectedArea: 0,
      affectedCount: 0,
    });
    this.waterLevelList = [];
    (this as any).$bus.$emit('waterLevelListHandler', []);
  }
  startDrawing(drawType) {

    this.workmap.startDrawing(drawType);
  }
  clearDrawing() {
    this.workmap.clearDrawing();
  }

  // 处理函数
 extractIndexData(data, index) {
  const result: Array<{
    name: string;
    count: number;    
    position:string;
    departName: string;
  }> = [];

  // 遍历部门信息
  if(data && data.departInfo){
    for (const depart of data.departInfo) {
      // 获取部门名称
      const departName =data.departMap[depart.departId] || '未知部门';

      // 筛选并处理 detailList
      depart.detailList.forEach(item => {
        if (item.index === index) {
          result.push({
            name: item.codeName,
            count: item.count,
            position: item.position,
            departName
          });
        }
      });
    }
  }
  return result;
}

  updateRadiusKm() {

    if (this.models.radiusKm >= 0 && this.models.hasWater) {

      this.workmap.createCircleByPolygonHandler();

    }
  }

  searchAddressHandler(name) {

    if (this.isLatLong(name)) {
      this.workmap.updatePosition(name.split(','))
      return;
    }
    this.workmap.searchFeature(name);

  }
  isLatLong(str) {
    const [lat, long] = str.split(',');
    if (isNaN(lat) || isNaN(long)) {
      return false;
    }
    return true;
  }

  startSearch(event) {
    if (event.target.classList.contains('el-input__icon') && this.models.searchName) {
      console.log('后缀图标被点击');
      this.searchAddressHandler(this.models.searchName);
      // 这里写你的点击逻辑
    }

  }
  created() {
    this.debouncedHandleSearch = _.debounce(this.startSearch, 1000);
    geoJson({ all: true }).then(res => {
      if (res.data.features.length > 0) {
        this.workmap.addSource(res.data);
      }
    })
  }
}
</script>
<style lang="scss" scoped>
.statistics {
  display: flex;

  .box-left {
    height: auto;
  }

  .box-right {
    flex: 1;
    padding: 0px;
    display: flex;
    flex-direction: column;
    gap: 0px;
  }
}

.boundary-topleft {
  background-color: #fff;
  position: absolute;
  padding: 10px;
  top: 30px;
  left: 18px;
  z-index: 1000;
}

.boundary-right {
  background-color: #fff;
  position: absolute;
  padding: 10px;
  top: 20px;
  right: 1px;
  z-index: 1000;
}

.boundary-bootom {
  background-color: #fff;
  position: absolute;
  padding: 10px;
  bottom: 0px;
  left: 1px;
  width: 100%;
  z-index: 1000;
}

.boundary-left {
  background-color: #fff;
  opacity: 0.8;
  position: absolute;
  padding: 10px;
  top: 100px;
  left: 1px;
  z-index: 1000;
  color: darkgreen;
}
</style>
